package de.saar.penguin.give2.mapviewer;

import give.world.World;
import give.world.WorldManager;
import give.world.parser.ParseException;
import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.swing.JFrame;

import de.saar.basic.filewatcher.FileChangeListener;
import de.saar.basic.filewatcher.FileWatcher;
import give.util.StringTools;

/**
 * Hello world!
 *
 */
public class Main {
    public static String worldFile;
    static Main x;
    static MapViewerFrame frame;

    public static void main(String[] args) throws IOException, ParseException {
        x = new Main();
        worldFile = args[0];

        FileWatcher fw = new FileWatcher(new File(args[0]), 1);
        fw.addFileChangeListener(new TestListener());
        fw.startWatching();

        x.doIt(worldFile);
    }

    public void doIt(String filename) throws IOException, ParseException {
        WorldManager manager = new WorldManager();
        manager.readWorld(StringTools.makeUrlFromName(filename));
        World world = manager.getRandomWorld();

        frame = new MapViewerFrame(filename + " - GIVE-2 Map Viewer", world);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.addControllerArrows();
        frame.addTooltips();

        frame.getMapViewer().setShowPlayerIcon(true);

        frame.display();
    }

    private static class TestListener implements FileChangeListener {
        public void fileChanged(File file, long lastModificationTime) {
            System.err.println(file + " changed at " + new Date(lastModificationTime));
            try {
                WorldManager manager = new WorldManager();
                manager.readWorld(StringTools.makeUrlFromName(worldFile));
                World world = manager.getRandomWorld();

                frame.open(world);
                frame.addControllerArrows();
                frame.addTooltips();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
